﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Data;
using System.Data.SQLite;
using System.Threading;
using System.Diagnostics;


namespace MosaicPowerMonitor
{
    class controller
    {
        public static SQLiteConnection coeff;
        public static SQLiteConnection poweruse;
        public static PerformanceCounter cpuCounter;

        public static void SetConnection()
        {
            String connectionString = "data source=" + "C:\\Mosaic\\Coefficients" +";Version=3;";
            coeff = new SQLiteConnection(connectionString);
        } 

        static void Main()
        {
            SetConnection();
            try
            {
                coeff.Open();
            }
            catch (Exception)
            {
                Console.WriteLine("not open");
            }

            SQLiteCommand readalpha = new SQLiteCommand("SELECT Alpha FROM Main WHERE (Model = 'Toshiba LE')", coeff);
            object value = readalpha.ExecuteScalar();
            SQLiteCommand readbaseline = new SQLiteCommand("SELECT Baseline FROM Main WHERE (Model = 'Toshiba LE')", coeff);
            object value2 = readbaseline.ExecuteScalar();
            double alpha = System.Convert.ToDouble(value.ToString());
            double baseline = System.Convert.ToDouble(value2.ToString());
            SQLiteCommand create = new SQLiteCommand("CREATE TABLE IF NOT EXISTS Power(Time TIMESTAMP, Power FLOAT)",coeff);
            create.ExecuteNonQuery();

            while (true)
            {
                cpuCounter = new PerformanceCounter();
                cpuCounter.CategoryName = "Processor";
                cpuCounter.CounterName = "% Processor Time";
                cpuCounter.InstanceName = "_Total";
                double cpu = System.Convert.ToDouble(getCurrentCpuUsage());

                double power = alpha * cpu + baseline;
                Console.WriteLine("Alpha = " + alpha + " CPU Usage = " + cpu);
                Console.WriteLine("So power usage = " + power + "%");

                SQLiteCommand storepower = new SQLiteCommand("INSERT INTO Power(Power) values ('" + power + "' )", coeff);
                storepower.ExecuteNonQuery();
                Thread.Sleep(2000);
            }
        }

        public static float getCurrentCpuUsage()
        {
            cpuCounter.NextValue();
            Thread.Sleep(1000);
            return cpuCounter.NextValue();
        }

    }
}
